package cn.maxxieyi.aichatbot.holder;

import cn.hutool.extra.spring.SpringUtil;
import cn.maxxieyi.aichatbot.enums.AiTypeEnum;
import cn.maxxieyi.aichatbot.service.AiApiService;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;


/**
 * 存储 AiService 实例
 */
@Component
public class AiApiServiceHolder {

    private Map<String, AiApiService> holder = new HashMap<>(32);

    /**
     * 给每个渠道，每种消息类型初始化一个线程池
     */
    @PostConstruct
    public void init() {
        for (AiTypeEnum aiTypeEnum : AiTypeEnum.values()) {

            Class serviceClass = aiTypeEnum.getServiceClass();
            holder.put(aiTypeEnum.getType(), (AiApiService)SpringUtil.getBean(serviceClass));
        }
    }

    /**
     * 得到对应的AiApiService
     *
     * @param aiType
     * @return
     */
    public AiApiService getService(String aiType) {
        AiApiService aiApiService = holder.get(aiType);
        if(aiApiService==null){
            Class serviceClass = AiTypeEnum.getServiceClassByType(aiType);
            if(serviceClass!=null) {
                aiApiService = (AiApiService) SpringUtil.getBean(serviceClass);
                holder.put(aiType, aiApiService);
            }
        }
        return aiApiService;
    }


}
